﻿using Common;
using enterprise.Website.Core.Filter;
using FreeSql.Context;
using FreeSql.Model;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace enterprise.Website.Core.ApiControllers
{
    /// <summary>
    /// 语言类型管理
    /// </summary>
    [Route("api/[controller]")]
    [ApiController]
    [LoginAuthorize]
    public class LanguageTypeController : ControllerBase
    {
        private readonly SqlContext _sqlContext;
        private readonly ICache _cache;
        private readonly IWebHostEnvironment _hostingEnvironment;
        public LanguageTypeController(SqlContext sqlContext, ICache cache, IWebHostEnvironment hostingEnvironment)
        {
            _cache = cache;
            _sqlContext = sqlContext;
            _hostingEnvironment = hostingEnvironment;
        }

        /// <summary>
        /// 获取语言版本管理列表
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<PageModel<LanguageType>> Get(int page=1,int limit = 10)
        {
            return await _sqlContext.QueryPageListAsync<LanguageType>(page: 1, limit: 10);
        }

        /// <summary>
        /// 查询所有语言类型下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet("QueryLanguageSelect")]
        public async Task<object> QueryLanguageSelect()
        {
            var list = await _sqlContext.QueryListAsync<LanguageType>();
            if (list != null && list.Count > 0)
            {
                return list.Select(m => new { text = m.Language, value = m.Id }).ToList();
            }
            else
            {
                return new List<object>();
            }
        }

        /// <summary>
        /// 新增语言
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Post([FromBody] LanguageType data)
        {

            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (AppSetting.IsNeedValid)
            {
                var LookchemToken = HttpContext.Session.GetString(SystemConstConfig.LookchemLogin);
                var IsLookchemLogin = false;
                if (!LookchemToken.IsNullOrWhiteSpace())
                {
                    IsLookchemLogin = ApiLogin.TokenLogin(LookchemToken, string.Empty, HttpContext.Request.Host.Host).Result;
                }
                if (!IsLookchemLogin)
                {
                    result.Message = "如需增加语言版本，请联系销售经理!";
                    return result;
                }
            }
            if (data != null)
            {
                if (data.LanguageClass.IsNullOrWhiteSpace())
                {
                    result.Message = "请填写语言路径";
                    return result;
                }
                if (data.LanguageClass.IsChinese())
                {
                    result.Message = "语言路径不能包含中文";
                    return result;
                }
                if (data.LanguageClass.Length > 2)
                {
                    result.Message = "语言路径最多填写两个字符";
                    return result;
                }
                if (data.IsDefault == 1)
                {
                    await _sqlContext.UpdateAsync<LanguageType>(m => new LanguageType { IsDefault = 0 }, n => true);
                }
                var Id=await _sqlContext.AddAsync(data);
                if (Id > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove(SystemConstConfig.CacheLanguageType);
                }
            }
            return result;
        }

        /// <summary>
        /// 编辑语言(弹窗)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="data"></param>
        [HttpPut("{id}")]
        public async Task<ApiResult> Put(int id, [FromBody] LanguageType data)
        {
            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (AppSetting.IsNeedValid)
            {
                var LookchemToken = HttpContext.Session.GetString(SystemConstConfig.LookchemLogin);
                var IsLookchemLogin = false;
                if (!LookchemToken.IsNullOrWhiteSpace())
                {
                    IsLookchemLogin = ApiLogin.TokenLogin(LookchemToken, string.Empty, HttpContext.Request.Host.Host).Result;
                }
                if (!IsLookchemLogin)
                {
                    result.Message = "如需增加语言版本，请联系销售经理!";
                    return result;
                }
            }
            if (data != null)
            {
                if (data.LanguageClass.IsNullOrWhiteSpace())
                {
                    result.Message = "请填写语言路径";
                    return result;
                }
                if (data.LanguageClass.IsChinese())
                {
                    result.Message = "语言路径不能包含中文";
                    return result;
                }
                if (data.LanguageClass.Length > 2)
                {
                    result.Message = "语言路径最多填写两个字符";
                    return result;
                }
                if (data.IsDefault == 1)
                {
                    await _sqlContext.UpdateAsync<LanguageType>(m => new LanguageType { IsDefault = 0 }, n => true);
                }
                var Count = await _sqlContext.UpdateAsync(data);
                if (Count > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove(SystemConstConfig.CacheLanguageType);
                }
            }
            return result;
        }

        /// <summary>
        /// 编辑语言(列表)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="data"></param>
        [HttpPut("table/{id}")]
        public async Task<ApiResult> PutTable(int id, [FromBody] LanguageType data)
        {
            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (AppSetting.IsNeedValid)
            {
                var LookchemToken = HttpContext.Session.GetString(SystemConstConfig.LookchemLogin);
                var IsLookchemLogin = false;
                if (!LookchemToken.IsNullOrWhiteSpace())
                {
                    IsLookchemLogin = ApiLogin.TokenLogin(LookchemToken, string.Empty, HttpContext.Request.Host.Host).Result;
                }
                if (!IsLookchemLogin)
                {
                    result.Message = "如需增加语言版本，请联系销售经理!";
                    return result;
                }
            }
            if (data != null)
            {
                if (data.LanguageClass.IsNullOrWhiteSpace())
                {
                    result.Message = "请填写语言路径";
                    return result;
                }
                if (data.LanguageClass.IsChinese())
                {
                    result.Message = "语言路径不能包含中文";
                    return result;
                }
                if (data.LanguageClass.Length > 2)
                {
                    result.Message = "语言路径最多填写两个字符";
                    return result;
                }
                var Count = await _sqlContext.UpdateAsync<LanguageType>(m => new LanguageType
                {
                    Language = data.Language,
                    LanguageClass = data.LanguageClass
                }, n => n.Id == id);
                if (Count > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove(SystemConstConfig.CacheLanguageType);
                }
            }
            return result;
        }

        /// <summary>
        /// 编辑语言(修改默认)
        /// </summary>
        /// <param name="id"></param>
        /// <param name="data"></param>
        [HttpPut("setDefault/{id}")]
        public async Task<ApiResult> SetDefault(int? id ,[FromForm]int? isDefault)
        {
            var result = new ApiResult { Success = false, Message = "保存失败" };
            if (id.HasValue&& isDefault.HasValue)
            {
                if (isDefault.Value == 1)
                {
                    await _sqlContext.UpdateAsync<LanguageType>(m => new LanguageType { IsDefault = 0 }, n => true);
                }
                var Count = await _sqlContext.UpdateAsync<LanguageType>(m => new LanguageType
                {
                    IsDefault= isDefault.Value
                }, n => n.Id == id.Value);
                if (Count > 0)
                {
                    result.Success = true;
                    result.Message = "保存成功";
                    _cache.Remove(SystemConstConfig.CacheLanguageType);
                }
            }
            return result;
        }

        /// <summary>
        /// 删除语言
        /// </summary>
        /// <param name="id"></param>
        [HttpDelete("{id}")]
        public async Task<ApiResult> Delete(int id = 0)
        {
            var result = new ApiResult { Success = false, Message = "删除失败" };
            if (AppSetting.IsNeedValid)
            {
                var LookchemToken = HttpContext.Session.GetString(SystemConstConfig.LookchemLogin);
                var IsLookchemLogin = false;
                if (!LookchemToken.IsNullOrWhiteSpace())
                {
                    IsLookchemLogin = ApiLogin.TokenLogin(LookchemToken, string.Empty, HttpContext.Request.Host.Host).Result;
                }
                if (!IsLookchemLogin)
                {
                    result.Message = "如需增加语言版本，请联系销售经理!";
                    return result;
                }
            }
            if (id>0)
            {
                var languageTypeInfo = await _sqlContext.QueryInfoAsync<LanguageType>(m => m.Id == id);
                if (languageTypeInfo != null)
                {
                    var hasContentClass = await _sqlContext.QueryCountAsync<ContentClass>(m => m.LanguageId == id);
                    if (hasContentClass > 0)
                    {
                        result.Success = false;
                        result.Message = "该语言下有网站栏目，无法删除";
                        return result;
                    }
                    var hasLanguageText = await _sqlContext.QueryCountAsync<LanguageText>(m => m.LanguageId == id);
                    if (hasContentClass > 0)
                    {
                        result.Success = false;
                        result.Message = "该语言下有标签，无法删除";
                        return result;
                    }
                    var Count = await _sqlContext.DeleteAsync<LanguageType>(m => m.Id == id);
                    if (Count > 0)
                    {
                        result.Success = true;
                        result.Message = "删除成功";
                        _cache.Remove(SystemConstConfig.CacheLanguageType);
                        //如果有图标，则删除对应的图标
                        if (!languageTypeInfo.LanguageImg.IsNullOrWhiteSpace())
                        {
                            string filePath = _hostingEnvironment.WebRootPath + languageTypeInfo.LanguageImg;
                            if (System.IO.File.Exists(filePath))//如果存在此文件，将其删除
                            {
                                System.IO.File.Delete(filePath);
                            }
                        }
                    }
                }
            }
            return result;
        }
    }
}
